import { listUserTrainingPlanRelationVoByPageUsingPost } from '@/services/backend/userTrainingPlanRelationController';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import { useModel } from '@umijs/max';
import React, { useRef, useState } from 'react';

interface TableRuleListItem extends API.TrainingRule {
  status: string;
}

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();

  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser ?? {};

  const [expandedRowKeys, setExpandedRowKeys] = useState<React.Key[]>([]); // 用于管理展开的行

  const expandedRowRender = (record: API.UserTrainingPlanRelationVO) => {
    // 假设 record 中有一个属性 `rules`，它是一个数组，包含了与该行相关的规则数据
    //@ts-ignore
    const data: TableRuleListItem[] = record?.trainingPlan?.ruleList || []; // 从当前行获取规则数据

    const columns: ProColumns<TableRuleListItem>[] = [
      {
        title: '规则名称',
        dataIndex: 'ruleName',
        valueType: 'text',
      },
      {
        title: '状态',
        dataIndex: 'status',
        valueType: 'select',
        valueEnum: {
          0: { text: '未完成', status: '0' },
          1: { text: '已完成', status: '1' },
        },
      },
    ];

    return (
      <ProTable
        rowKey="id"
        columns={columns}
        dataSource={data} // 使用从当前行获取的数据
        headerTitle={false}
        search={false}
        options={false}
        pagination={false}
      />
    );
  };

  const columns: ProColumns<API.UserTrainingPlanRelationVO>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'text',
      hideInForm: true,
    },
    {
      title: '训练名称',
      dataIndex: ['trainingPlan', 'planName'],
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: {
        active: { text: '正在进行', status: 'ongoing' },
        archived: { text: '已完成', status: 'completed' },
      },
    },
    {
      title: '创建时间',
      sorter: true,
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
    {
      title: '更新时间',
      sorter: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      hideInSearch: true,
      hideInForm: true,
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.UserTrainingPlanRelation>
        headerTitle={'查询表格'}
        actionRef={actionRef}
        rowKey="id" // 确保使用数据中的唯一标识字段
        expandable={{
          expandedRowRender,
          expandedRowKeys,
          onExpand: (expanded, record) => {
            console.log('setCurrentRow', record);
            if (expanded) {
              // 添加当前行id到展开数组
              //@ts-ignore
              setExpandedRowKeys([record.id]);
            } else {
              // 从展开数组中移除当前行id
              setExpandedRowKeys([]);
            }
          },
        }}
        search={{
          labelWidth: 120,
        }}
        request={async (params, sort, filter) => {
          const sortField = Object.keys(sort)?.[0];
          const sortOrder = sort?.[sortField] ?? undefined;
          const { data, code } = await listUserTrainingPlanRelationVoByPageUsingPost({
            ...params,
            sortField,
            sortOrder,
            ...filter,
          } as API.UserTrainingPlanRelationQueryRequest);

          const myData = data?.records?.filter((item) => {
            return item.userId === currentUser.id;
          });

          return {
            success: code === 0,
            data: myData || [],
            total: Number(data?.total) || 0,
          };
        }}
        columns={columns}
      />
    </PageContainer>
  );
};
export default TableList;
